﻿using System.Threading.Tasks;
using Microsoft.Data.Sqlite;

namespace OpenAiClient.Util.Database
{
    // ReSharper disable once IdentifierTypo
    public class SqliteHelper
    {
        public string ConnectionString { get; set; }

        /// <summary>
        /// 准备数据库
        /// </summary>
        public async Task PrepareDatabaseAsync()
        {
            using (var connection = new SqliteConnection(ConnectionString))
            {
                await connection.OpenAsync();
                connection.Close();
            }
        }

        /// <summary>
        /// 执行不带参数的sql语句
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public async Task<int> ExecuteNonQueryAsync(string sql)
        {
            return await ExecuteNonQueryAsync(sql, null);
        }

        /// <summary>
        /// 执行带参数的sql语句
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <param name="paras">参数</param>
        /// <returns>影响的记录数</returns>
        public async Task<int> ExecuteNonQueryAsync(string sql, SqliteParameter[] paras)
        {
            using (var connection = new SqliteConnection(ConnectionString))
            {
                await connection.OpenAsync();

                var command = connection.CreateCommand();
                command.CommandText = sql;

                if (paras != null)
                {
                    command.Parameters.AddRange(paras);
                }

                return await command.ExecuteNonQueryAsync();
            }
        }
    }
}
